package org.smarthings.things.events.processing;

import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;

public class ThingEventStreamSpout implements EventHandler {

//	private EPServiceProvider eventProcessingService;
	private ServiceRegistration eventHangerRegistration;
	private ComplexEventProcessingEngine eventProcessingService;

	private String[] topics;

	public ThingEventStreamSpout(ComplexEventProcessingEngine eventProcessingService, List<String> topics) {
		this.eventProcessingService = eventProcessingService;
		this.topics = topics.toArray(new String[topics.size()]);
	}

	@Override
	public void handleEvent(Event event) {
		System.out.println("ThingEventStreamSpout.handleEvent : " + event);
		String[] propertyNames = event.getPropertyNames();
		Map<String, Object> properties = new HashMap<String, Object>(propertyNames.length);
		for (int i = 0; i < propertyNames.length; i++) {
			properties.put(propertyNames[i], event.getProperty(propertyNames[i]));
		}
//		eventProcessingService.getEPRuntime().sendEvent(properties, event.getTopic());
		eventProcessingService.feedEvent(event);

	}

	public void register(ComponentContext context) {
		Dictionary<String, Object> properties = new Hashtable<String, Object>(2);
		properties.put(EventConstants.EVENT_TOPIC, topics);
		eventHangerRegistration = context.getBundleContext().registerService(
				EventHandler.class.getName(), this, properties);
	}

	public void unregister(ComponentContext context) {
		if (eventHangerRegistration != null) {
			eventHangerRegistration.unregister();
			eventHangerRegistration = null;
		}

	}

}
